/**
 * 流量超市企业主体配置
 */
import { failed } from '@gnlab/utils'
import { App } from 'antd'
import { appsAPI } from '@/services/common/api'

export function useAppsCorps() {
  const { message } = App.useApp()

  const [appsCorps, setAppsCorps] = useState<AppsCorpInfo[] | null>(null)
  const load = useCallback(async () => {
    const res = await getAppsCorps()
    if (res.success) setAppsCorps(res.data ?? [])
    else {
      void message.warning(`主体列表加载失败 ${res.error.code}:${res.error.message}`)
      setAppsCorps(corps => corps ?? [])
    }
  }, [message])

  return {
    appsCorps,
    loadAppsCorps: load,
  }
}

/**
 * 企业列表
 */
export interface AppsCorpInfo {
  corpId: string
  corpName: string
}
export async function getAppsCorps() {
  return appsAPI<AppsCorpInfo[] | null>('/qywx/corps')
}

/**
 * 企业详情
 */
export interface AppsCorpDetail {
  // 基本信息
  corpId: string
  corpName: string
  secret: string

  // “接收事件”配置
  cryptKey: string
  cryptToken: string
  pushURL: string

  // “企业微信 - 自建应用”配置（也是“被删除通知”配置）
  appSwitch: boolean
  appAgent: number
  appSecret: string
}
export async function getAppsCorpDetail(corpId: string) {
  return appsAPI<AppsCorpDetail>(`/qywx/corp?corpId=${corpId}`)
}

/**
 * 添加企业
 */
export type AppsCorpEditInfo = Pick<AppsCorpDetail, 'corpId' | 'corpName' | 'secret'>
export async function addAppsCorp(params: AppsCorpEditInfo) {
  const res = await appsAPI('/qywx/corp', {
    method: 'POST',
    data: params,
  })
  if (!res.success) {
    if (res.error.code === 65624) {
      return failed({ code: res.error.code, message: '企业已存在，请勿重复添加' })
    } else {
      return failed({ code: res.error.code, message: '请填写有效的 CorpID 和 Secret' })
    }
  }
  return res
}

/**
 * 修改企业
 */
export async function updateAppsCorp(params: AppsCorpEditInfo & { oldCorpId: string }) {
  const res = await appsAPI('/qywx/corp', {
    method: 'PUT',
    data: params,
  })
  if (!res.success) {
    if (res.error.code === 65624) {
      return failed({ code: res.error.code, message: '企业已存在，请勿重复添加' })
    } else {
      return failed({ code: res.error.code, message: '请填写有效的 CorpID 和 Secret' })
    }
  }
  return res
}

// 重置接收事件服务器设置
export async function resetAppsCorpServer(oldCorpId: string) {
  return appsAPI('/qywx/server', {
    method: 'PUT',
    data: { oldCorpId },
  })
}
